package com.dqhl.community.activity;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.GridViewWithHeaderAndFooter;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.dqhl.community.R;
import com.dqhl.community.adapter.GoodsSelectRootListAdapter;
import com.dqhl.community.adapter.GoodsSelectSubListAdapter;
import com.dqhl.community.adapter.ShoppingOnlineAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.Goods;
import com.dqhl.community.model.SelectGoods;
import com.dqhl.community.util.ACache;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.ScreenUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liming on 2016/9/5.
 * 在线超市
 */
public class ShoppingOnlineActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvback;
    private TextView mTvTitle;
    private GridViewWithHeaderAndFooter mGvShopping;
    private TextView tv_select_goods; //按类别选择商品
    private TextView tv_no_data;

    private PopupWindow mPopupWindow;
    private ListView rootListView; //根目录
    private ListView subListView; //二级目录
    private LinearLayout popupLayout; //弹出popupwindow布局
    private FrameLayout subLayout; //子目录布局
    private int selectedPosition; //根目录被选中的节点
    private List<SelectGoods> rootGoodsList;
    private List<SelectGoods> subGoodsList;
    private List<Goods> selectResultGoodsList; //通过一二级选择出的商品结果
    private ShoppingOnlineAdapter shoppingOnlineAdapter;
    private GoodsSelectRootListAdapter adapter;
    private ACache aCache; //缓存类
    private boolean isFirstIn;
    private PtrClassicFrameLayout ptrClassicFrameLayout;
    Handler handler = new Handler();
    private int page = 1;
    private String son_id = ""; //节点Id

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_online);
        isFirstIn = true;
        Dlog.e("初始化ACache，isFirstIn:" + isFirstIn);
        aCache = ACache.get(ShoppingOnlineActivity.this);
        initView();
        showRecommend();
        initData();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mIvback = (ImageView) findViewById(R.id.iv_top_back);
        mTvTitle = (TextView) findViewById(R.id.tv_top_title);
        mGvShopping = (GridViewWithHeaderAndFooter) findViewById(R.id.gv_shopping);
        tv_select_goods = (TextView) findViewById(R.id.tv_select_goods);
        tv_no_data = (TextView) findViewById(R.id.tv_no_data);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) findViewById(R.id.ptr_list);
        mIvback.setVisibility(View.VISIBLE);
        mIvback.setOnClickListener(this);
        mTvTitle.setText("在线超市");
        tv_select_goods.setOnClickListener(this);

    }

    /**
     * 推荐商品
     */
    private void showRecommend() {
        showCustomLoadBar("加载中……");
        RequestParams params = new RequestParams(Config.Api.recommend);
        params.addBodyParameter("userid", app.getUserId());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    mGvShopping.setVisibility(View.VISIBLE);
                    tv_no_data.setVisibility(View.GONE);
                    selectResultGoodsList = new ArrayList<Goods>(
                            JSONArray.parseArray(data, Goods.class)
                    );
                    Dlog.e("selectResultGoodsList:" + selectResultGoodsList.toString());
                    shoppingOnlineAdapter = new ShoppingOnlineAdapter(ShoppingOnlineActivity.this,
                            selectResultGoodsList);
                    shoppingOnlineAdapter.setOnBuyClickListener(new ShoppingOnlineAdapter.onBuyClickListener() {
                        @Override
                        public void doBuy(String goodsId, String strImg, String strName, String strPrice) {
                            Dlog.e("clicked goodsId:" + goodsId);
                            //跳到结算界面
                            Bundle bundle = new Bundle();
                            bundle.putString("total_money", strPrice);
                            bundle.putInt("number", 1);
                            bundle.putString("img", strImg);
                            bundle.putString("name", strName);
                            bundle.putString("goods_id", goodsId);
                            bundle.putString("price", strPrice);
                            overlay(ShoppingPaymentActivity.class, bundle);
                        }
                    });
                    shoppingOnlineAdapter.notifyDataSetChanged();
                    mGvShopping.setAdapter(shoppingOnlineAdapter);
                    mGvShopping.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            String goods_id = selectResultGoodsList.get(i).getId();
                            Dlog.e("传到详情页的goods_id为：" + goods_id);
                            Bundle bundle = new Bundle();
                            bundle.putString("goods_id", goods_id);
                            overlay(ShopOnlinDetailActivity.class, bundle);
                        }
                    });

                } else if (errCode == 4014) { //没有商品
                    mGvShopping.setVisibility(View.GONE);
                    tv_no_data.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 显示选择的商品
     */
    private void showSelectResult(String id) {
        Dlog.e(son_id +" showSelectResult  son_id " +id);
        showCustomLoadBar("加载中……");
        RequestParams params = new RequestParams(Config.Api.supermarket);
        params.addBodyParameter("son_id", id);
        params.addBodyParameter("userid", app.getUserId());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    mGvShopping.setVisibility(View.VISIBLE);
                    tv_no_data.setVisibility(View.GONE);
                    selectResultGoodsList = new ArrayList<Goods>(
                            JSONArray.parseArray(data, Goods.class)
                    );
                    Dlog.e("selectResultGoodsList:" + selectResultGoodsList.toString());
                    shoppingOnlineAdapter = new ShoppingOnlineAdapter(ShoppingOnlineActivity.this,
                            selectResultGoodsList);
                    shoppingOnlineAdapter.setOnBuyClickListener(new ShoppingOnlineAdapter.onBuyClickListener() {
                        @Override
                        public void doBuy(String goodsId, String strImg, String strName, String strPrice) {
                            Dlog.e("clicked goodsId:" + goodsId);
                            //跳到结算界面
                            Bundle bundle = new Bundle();
                            bundle.putString("total_money", strPrice);
                            bundle.putInt("number", 1);
                            bundle.putString("img", strImg);
                            bundle.putString("name", strName);
                            bundle.putString("goods_id", goodsId);
                            bundle.putString("price", strPrice);
                            overlay(ShoppingPaymentActivity.class, bundle);
                        }
                    });
                    shoppingOnlineAdapter.notifyDataSetChanged();
                    mGvShopping.setAdapter(shoppingOnlineAdapter);
                    mGvShopping.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            String goods_id = selectResultGoodsList.get(i).getId();
                            Dlog.e("传到详情页的goods_id为：" + goods_id);
                            Bundle bundle = new Bundle();
                            bundle.putString("goods_id", goods_id);
                            overlay(ShopOnlinDetailActivity.class, bundle);
                        }
                    });

                } else if (errCode == 4014) { //没有商品
                    toast("没有商品");
                    mGvShopping.setVisibility(View.GONE);
                    tv_no_data.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.tv_select_goods:
                showSelectGoodsPopupWindow();
                break;
        }
    }


    /**
     * 显示选择商品的二级菜单
     */
    private void showSelectGoodsPopupWindow() {
        LayoutInflater inflater = LayoutInflater.from(ShoppingOnlineActivity.this);
        popupLayout = (LinearLayout) inflater.inflate(
                R.layout.popupwindow_select_goods, null, false);
        rootListView = (ListView) popupLayout.findViewById(R.id.root_listview);
        if (isFirstIn) {
            Dlog.e("isFirstIn:" + isFirstIn);
            getRootGoodsList();
        } else {
            Dlog.e("isFirstIn:" + isFirstIn);
            String result = aCache.getAsString("rootGoodsCache");
            Dlog.e("result:" + result);
            parseRootGoodsList(result);
        }
    }

    /**
     * 获取一级列表
     */
    private void getRootGoodsList() {
        showCustomLoadBar("加载中…");
        RequestParams params = new RequestParams(Config.Api.supermarketType);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                aCache.put("rootGoodsCache", result);
                Dlog.e("aCache.get:" + aCache.getAsString("rootGoodsCache"));
                if (aCache.getAsString("rootGoodsCache") != null && aCache.getAsString("rootGoodsCache").length() > 0) {
                    isFirstIn = false;
                }
                parseRootGoodsList(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });

    }

    /**
     * 解析一级列表
     *
     * @param result
     */
    private void parseRootGoodsList(String result) {
        int errCode = JsonUtils.getErrCode(result);
        String data = JsonUtils.getInfo(result, "data");
        if (errCode == 0) {
            rootGoodsList = new ArrayList<SelectGoods>(
                    JSONArray.parseArray(data, SelectGoods.class)
            );
            Dlog.e("rootList:" + rootGoodsList.toString());
            if (rootGoodsList.size() > 0) {
                adapter = new GoodsSelectRootListAdapter(
                        ShoppingOnlineActivity.this, rootGoodsList);
                rootListView.setAdapter(adapter);
                // 子popupWindow
                subLayout = (FrameLayout) popupLayout.findViewById(R.id.sub_popupwindow);
                // 初始化subListview
                subListView = (ListView) popupLayout.findViewById(R.id.sub_listview);
                // 弹出popupwindow时，二级菜单默认隐藏，当点击某项时，二级菜单再弹出
                subLayout.setVisibility(View.INVISIBLE);
                // 初始化 mPopupWindow
                mPopupWindow = new PopupWindow(popupLayout, ScreenUtils.getScreenWidth(ShoppingOnlineActivity.this),
                        WindowManager.LayoutParams.WRAP_CONTENT, true);
                /**
                 * 有了mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                 * 这句可以使点击popupwindow以外的区域时popupwindow自动消失 但这句必须放在showAsDropDown之前
                 */
                mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                /**
                 * popupwindow的位置，第一个参数表示位于哪个控件之下 第二个参数表示向左右方向的偏移量，正数表示向左偏移，负数表示向右偏移
                 * 第三个参数表示向上下方向的偏移量，正数表示向下偏移，负数表示向上偏移
                 *
                 */
                mPopupWindow.showAsDropDown(tv_select_goods, -5, 5);// 在控件下方显示popwindow
                mPopupWindow.update();

                rootListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        // 选中root某项时改变该ListView item的背景色
                        adapter.setSelectedPosition(i);
                        adapter.notifyDataSetInvalidated();
                        selectedPosition = i;
                        String selectTypeId = rootGoodsList.get(i).getId();
                        Dlog.e("root select :" + rootGoodsList.get(i).getName() + ";" + rootGoodsList.get(i).getId());
                        getSubGoodsList(selectTypeId, i);
                    }
                });
            }
        }
    }

    /**
     * 获取二级列表
     */
    private void getSubGoodsList(String typeId, final int position) {
        showCustomLoadBar("加载中…");
        RequestParams params = new RequestParams(Config.Api.supermarketSon);
        params.addBodyParameter("type_id", typeId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                parseSubGoodsList(result, position);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 解析二级列表
     *
     * @param result
     * @param position
     */
    private void parseSubGoodsList(String result, int position) {
        int errCode = JsonUtils.getErrCode(result);
        String data = JsonUtils.getInfo(result, "data");
        if (errCode == 0) {
            subGoodsList = new ArrayList<SelectGoods>(
                    JSONArray.parseArray(data, SelectGoods.class)
            );
            Dlog.e("subList:" + subGoodsList.toString());

            GoodsSelectSubListAdapter subAdapter = new GoodsSelectSubListAdapter(
                    ShoppingOnlineActivity.this, subGoodsList, position
            );
            subListView.setAdapter(subAdapter);

            // 选中某个根节点时，使显示相应的子目录可见
            subLayout.setVisibility(View.VISIBLE);
            subListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    popupLayout.setVisibility(View.GONE);
                    mPopupWindow.dismiss();
                    son_id = subGoodsList.get(i).getId();
                    Dlog.e("选择了：" + subGoodsList.get(i).getId() + ";" + subGoodsList.get(i).getName());
//                    initData();
                    showSelectResult(son_id);
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isFirstIn = true;
        aCache.remove("rootGoodsList");
        Dlog.e("清除了缓存：rootGoodsList");
    }

    //下拉刷新  上提加载
    private void initData() {

        ptrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh(true);
                ptrClassicFrameLayout.setLoadMoreEnable(true);
//                ptrClassicFrameLayout.setAutoLoadMoreEnable(false);
            }
        }, 150);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        Dlog.e("下拉下拉 +"+son_id);
                        //获取数据
                        if("".equals(son_id)){
                            showRecommend();
                        }else{
                            showSelectResult(son_id);
                        }
                        ptrClassicFrameLayout.refreshComplete();
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        ptrClassicFrameLayout.loadMoreComplete(true);
                        page++;
                        Dlog.e("GGpages" + page);
                        moreShowSelectResult(son_id);
                    }
                }, 1000);
            }
        });
    }

    private void moreShowSelectResult(String id) {
        showCustomLoadBar("加载中……");
        RequestParams params = new RequestParams(Config.Api.supermarket);
        params.addBodyParameter("son_id", id);
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("userid", app.getUserId());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    List<Goods> moreSelectResultGoodsList = new ArrayList<Goods>(
                            JSONArray.parseArray(data, Goods.class)
                    );
                    Dlog.e("moreSelectResultGoodsList:" + moreSelectResultGoodsList.toString());
                    selectResultGoodsList.addAll(moreSelectResultGoodsList);
                    shoppingOnlineAdapter.notifyDataSetChanged();
                } else if (errCode == 4014) { //没有商品
                    toast("没有更多商品");
//                    mGvShopping.setVisibility(View.GONE);
//                    tv_no_data.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }
}
